package com.itheima.stock.helper;

import com.google.common.util.concurrent.RateLimiter;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.response.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author CaiZhiMin
 * @created 2025/10/19 15:57
 * @description: 接口流量控制切面
 */
@Aspect
@Component
public class LimiterAspect {

    @Autowired
    private RateLimiter rateLimiter;

    @Pointcut("@annotation(com.itheima.stock.annotation.Limiter)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object limiter(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean flag = rateLimiter.tryAcquire();
        if (flag) {
            return joinPoint.proceed();
        } else {
            return ResponseResult.error(CodeEnum.OVER_CONCURRENT_NUM);
        }
    }
}
